package com.admin.service.impl;

import com.admin.common.context.DeclareContext;
import com.admin.common.enums.*;
import com.admin.common.exception.BizException;
import com.admin.common.shiro.ShiroUtils;
import com.admin.common.util.DateUtils;
import com.admin.component.declare.DeclareHandlerDispatcher;
import com.admin.domain.*;
import com.admin.mapper.*;
import com.admin.req.declare.*;
import com.admin.service.*;
import com.admin.vo.PageVO;
import com.admin.vo.ResultVO;
import com.admin.vo.declare.DeclareListVO;
import com.admin.vo.declareDetail.*;
import com.admin.vo.declareDetail.score.ScoreListVO;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author yangzhongliang
 * @date 2022/05/16
 */
@Slf4j
@Service
public class DeclareServiceImpl implements DeclareService {
    @Autowired
    private DeclareMapper declareMapper;
    @Autowired
    private DeclareBasicMapper declareBasicMapper;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private DeclareInstitutionMapper institutionMapper;
    @Autowired
    private DeclareDisasterPlanMapper disasterPlanMapper;
    @Autowired
    private DeclareDisasterFacilitiesMapper disasterFacilitiesMapper;
    @Autowired
    private DeclareScienceMapper declareScienceMapper;
    @Autowired
    private DeclareClassicCaseMapper classicCaseMapper;
    @Autowired
    private DeclareWeatherBureauMapper weatherBureauMapper;
    @Autowired
    private DeclareUpgradeMapper upgradeMapper;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private ScoreParamService scoreParamService;
    @Autowired
    private DeclareReturnService declareReturnService;
    @Autowired
    private DeclareLogService logService;
    @Autowired
    private DeclareScoreService declareScoreService;
    @Autowired
    private DeclareLogService declareLogService;
    @Autowired
    private RegionMapper regionMapper;
    @Autowired
    private RegionsService regionsService;
    @Autowired
    private SysParamService sysParamService;
    @Autowired
    private DeclareHandlerDispatcher declareHandlerDispatcher;

    /**
     * 查询 自己 申报的记录
     * @param pageIndex
     * @param pageSize
     * @param params
     * @return
     */
    @Override
    public ResultVO<PageVO<DeclareListVO>> getPageList(Integer pageIndex, Integer pageSize, Map<String, Object> params) {
        ResultVO<PageVO<DeclareListVO>> result = new ResultVO<>();
        PageVO<DeclareListVO> page = new PageVO<>(pageIndex, pageSize);
        List<DeclareListVO> declareListVOList = new ArrayList<>();
        // 查询总数  申报人员 - 只能看自己负责的社区
        params.put("createId", ShiroUtils.getUserId());
        Integer totalCount = declareMapper.countByMap(params);
        page.setTotalCount(totalCount);
        if (totalCount > 0) {
            // 查询管理员信息
            params.put("startIndex", page.getStartIndex());
            params.put("pageSize", page.getPageSize());
            List<Declare> declareList = declareMapper.selectByMap(params);
            if (!CollectionUtils.isEmpty(declareList)) {
                for (Declare declare : declareList) {
                    DeclareListVO itemVO = new DeclareListVO();
                    BeanUtils.copyProperties(declare, itemVO);

                    itemVO.setDeclareTypeStr(DeclareTypeEnum.getText(declare.getDeclareType()));
                    itemVO.setCreateTimeStr(DateUtils.format(declare.getCreateTime(), DateUtils.DATE_PATTERN_TIME));
                    declareListVOList.add(itemVO);
                }
            }
        }
        page.setData(declareListVOList);
        result.setData(page);
        result.setCode(EnumResult.SUCCESS.getCode());
        result.setMsg(EnumResult.SUCCESS.getMsg());
        return result;
    }


    @Transactional
    @Override
    public ResultVO save(Integer userId, DeclareReq declareReq) {
        //查询当前登录用户所属社区
        AdminDO adminDO = adminMapper.selectByPrimaryKey(userId);
        if (Objects.isNull(adminDO)) {
            throw new BizException(-1, "登录信息已失效,请重新登录!");
        }

        if (adminDO.getCurrentRoundDeclareSwitch() == 0) {
            throw new BizException(-1, "你申报功能暂未开启,请联系管理员!");
        }

        if (adminDO.getRole() == 0) {
            throw new BizException(-1, "你是管理员,暂无申报权限！");
        }

        DeclareContext declareContext = DeclareContext.builder().userId(userId).adminDO(adminDO).declareReq(declareReq).build();
        Declare declare = declareHandlerDispatcher.getHandler(DeclareTypeEnum.getEnum(declareReq.getDeclareType()).name()).declare(declareContext);
        return ResultVO.ok(declare.getId());
    }

    Declare saveDeclareBasic(Integer userId, AdminDO adminDO, DeclareReq declareReq) {
        //如果传id 走修改路线
        if (null != declareReq.getId() && declareReq.getId() > 0) {
            return ((DeclareService) AopContext.currentProxy()).update(userId, declareReq);
        }

        //校验是否已经提交过申报了
        isSubmitDeclare(userId);

        //主表
        Declare declare = new Declare();
        declare.setDeclareType(declareReq.getDeclareType());
        declare.setVillageName(adminDO.getVillageName());
        declare.setProvinceId(adminDO.getProvinceId());
        declare.setCityId(adminDO.getCityId());
        declare.setAreaId(adminDO.getAreaId());
        declare.setCountryId(adminDO.getCountryId());
        declare.setRegionAddress(adminDO.getRegionNames());

        //基础信息必填- 已完成状态
        declare.setBasicInfoStatus(ModuleIFinishStatusEnum.FINISHED.getKey());
        //申报评分状态
        declare.setScoreStatus(DeclareScoreStatusEnum.WAIT_SUBMIT.getKey());

        declare.setCreateId(adminDO.getUserId());
        declare.setCreateMobile(adminDO.getMobile());
        declare.setCreateName(adminDO.getRealname());
        declareMapper.insertSelective(declare);

        //保存基础信息
        saveDeclareBasic(declare.getId(), declareReq.getBasicReq());
        //新增日志
        saveLog(declare, DeclareLogTypeEnum.TYPE_10);
        return declare;
    }


    private void saveLog(Declare declare,  DeclareLogTypeEnum typeEnum) {
        DeclareLog declareLog = new DeclareLog();
        declareLog.setDeclareId(declare.getId());
        declareLog.setOperatorType(typeEnum.getKey());
        declareLog.setContent(ShiroUtils.getUser().getVillageName() + ","+ typeEnum.getName());
        declareLog.setRemark("");
        declareLog.setUserLevel(ShiroUtils.getMemberLevel());
        StringBuffer levelName = new StringBuffer();
        levelName.append(ShiroUtils.getUser().getCountryName()).append("【").append(ShiroUtils.getUser().getVillageName()).append("】");
        declareLog.setUserLevelName(levelName.toString());
        declareLog.setOperatorName(ShiroUtils.getUserName());
        logService.insertLog(declareLog);
    }

    @Override
    public Declare saveNormalDeclareInfo(DeclareContext declareContext) {
        Integer userId = declareContext.getUserId();
        AdminDO adminDO = declareContext.getAdminDO();
        DeclareReq declareReq = declareContext.getDeclareReq();

        //保存基础信息
        Declare declare = saveDeclareBasic(userId, adminDO, declareReq);
        if (Objects.isNull(declare)) {
            return null;
        }

        //制度机制
        saveDeclareInstitution(declare.getId(), declareReq.getInstitutionReq());
        //防灾准备
        saveDeclareDisasterPlan(declare.getId(), declareReq.getDisasterPlanReq());
        //防灾设施
        saveDeclareDisasterFacilities(declare.getId(), declareReq.getFacilitiesReq());
        //科普培训
        saveDeclareScience(declare.getId(), declareReq.getScienceReq());
        //典型案例
        saveDeclareClassicCase(declare.getId(), declareReq.getCaseReq());
        //区县气象局
        saveDeclareWeatherBureau(declare.getId(), declareReq.getWeatherBureauReq());
        //提标升级
        saveDeclareUpgrade(declare.getId(), declareReq.getUpgradeReq());

        return declare;
    }

    @Override
    public Declare saveUpgradeDeclareInfo(DeclareContext declareContext) {
        Integer userId = declareContext.getUserId();
        AdminDO adminDO = declareContext.getAdminDO();
        DeclareReq declareReq = declareContext.getDeclareReq();

        //保存基础信息
        Declare declare = saveDeclareBasic(userId, adminDO, declareReq);
        if (Objects.isNull(declare)) {
            return null;
        }

        //提标升级
        saveDeclareUpgrade(declare.getId(), declareReq.getUpgradeReq());

        return declare;
    }

    @Override
    public void saveDeclareBasic(Integer declareId, DeclareBasicReq basicReq) {
        if (Objects.isNull(basicReq)) {
            throw new BizException(-1, "基本情况必填!");
        }
        DeclareBasic declareBasic = new DeclareBasic();
        BeanUtils.copyProperties(basicReq, declareBasic);
        declareBasic.setDeclareId(declareId);
        DeclareBasic declareBasicOld = declareBasicMapper.getByDeclareId(declareId);
        if (!Objects.isNull(declareBasicOld)) {
            declareBasic.setId(declareBasicOld.getId());
            declareBasicMapper.updateByPrimaryKeySelective(declareBasic);
        } else {
            declareBasicMapper.insertSelective(declareBasic);
        }
    }

    @Override
    public void saveDeclareInstitution(Integer declareId, DeclareInstitutionReq institutionReq) {
        //封装参数
        if (Objects.isNull(institutionReq)) {
            return;
        }
        DeclareInstitution declareInstitution = new DeclareInstitution();
        BeanUtils.copyProperties(institutionReq, declareInstitution);
        declareInstitution.setDeclareId(declareId);
        //工作机制 - 支持上传多个文件
        declareInstitution.setOrgWorkFiles(attachmentService.uploadAttachment(declareId, institutionReq.getOrgWorkFiles()));
        //重点单位 - 重点单位
        if (!CollectionUtils.isEmpty(institutionReq.getHotCompanyReqs()))  {
            declareInstitution.setHotCompanys(JSONObject.toJSONString(institutionReq.getHotCompanyReqs()));
        }
        //服务站图片  stationImages
        declareInstitution.setStationImages(attachmentService.uploadAttachment(declareId, institutionReq.getStationImages()));
        //组织保障 - 投资证明图片
        declareInstitution.setEnsureImages(attachmentService.uploadAttachment(declareId, institutionReq.getEnsureImages()));
        //组织保障 - 投资证明文件
        declareInstitution.setEnsureFiles(attachmentService.uploadAttachment(declareId, institutionReq.getEnsureFiles()));

        //是否存在 - 存在
        DeclareInstitution declareInstitutionOld = institutionMapper.getByDeclareId(declareId);
        if (!Objects.isNull(declareInstitutionOld)) {
            declareInstitution.setId(declareInstitutionOld.getId());
            institutionMapper.updateByPrimaryKeySelective(declareInstitution);
        } else {
            institutionMapper.insertSelective(declareInstitution);
        }
    }

    @Override
    public void saveDeclareDisasterPlan(Integer declareId, DeclareDisasterPlanReq disasterPlanReq) {
        if (Objects.isNull(disasterPlanReq)) {
            return;
        }
        DeclareDisasterPlan disasterPlan = new DeclareDisasterPlan();
        BeanUtils.copyProperties(disasterPlanReq, disasterPlan);
        disasterPlan.setDeclareId(declareId);
        //风险地图
        disasterPlan.setMapImages(attachmentService.uploadAttachment(declareId, disasterPlanReq.getMapImages()));
        //应急预案或计划
        disasterPlan.setPlanFiles(attachmentService.uploadAttachment(declareId, disasterPlanReq.getPlanFiles()));
        //应急演练- 现场照片
        disasterPlan.setTrainImages(attachmentService.uploadAttachment(declareId, disasterPlanReq.getTrainImages()));

        DeclareDisasterPlan disasterPlanOld = disasterPlanMapper.getByDeclareId(declareId);
        if (!Objects.isNull(disasterPlanOld)) {
            disasterPlan.setId(disasterPlanOld.getId());
            disasterPlanMapper.updateByPrimaryKeySelective(disasterPlan);
        } else {
            disasterPlanMapper.insertSelective(disasterPlan);
        }
    }

    @Override
    public void saveDeclareDisasterFacilities(Integer declareId, DeclareDisasterFacilitiesReq facilitiesReq) {
        if (Objects.isNull(facilitiesReq)) {
            return;
        }
        DeclareDisasterFacilities disasterFacilities = new DeclareDisasterFacilities();
        BeanUtils.copyProperties(facilitiesReq, disasterFacilities);
        disasterFacilities.setDeclareId(declareId);
        //信息收发 - 现场照片
        disasterFacilities.setInfoImages(attachmentService.uploadAttachment(declareId, facilitiesReq.getInfoImages()));
        //避灾设施 - 现场照片
        disasterFacilities.setPlanImages(attachmentService.uploadAttachment(declareId, facilitiesReq.getPlanImages()));
        //防雷警示 - 现场照片
        disasterFacilities.setRemindImages(attachmentService.uploadAttachment(declareId, facilitiesReq.getRemindImages()));

        DeclareDisasterFacilities disasterFacilitiesOld = disasterFacilitiesMapper.getByDeclareId(declareId);
        if (!Objects.isNull(disasterFacilitiesOld)) {
            disasterFacilities.setId(disasterFacilitiesOld.getId());
            disasterFacilitiesMapper.updateByPrimaryKeySelective(disasterFacilities);
        } else {
            disasterFacilitiesMapper.insertSelective(disasterFacilities);
        }
    }

    @Override
    public void saveDeclareScience(Integer declareId, DeclareScienceReq declareScienceReq) {
        if (Objects.isNull(declareScienceReq)) {
            return;
        }

        DeclareScience declareScience = new DeclareScience();
        BeanUtils.copyProperties(declareScienceReq, declareScience);
        //培训 - 证明培训图片
        declareScience.setTrainImages(attachmentService.uploadAttachment(declareId,declareScienceReq.getTrainImages()));
        //培训 - 证明培训文件
        declareScience.setTrainFiles(attachmentService.uploadAttachment(declareId, declareScienceReq.getTrainFiles()));
        // 科普 - 活动现场拍摄图片
        declareScience.setScienceImages(attachmentService.uploadAttachment(declareId, declareScienceReq.getScienceImages()));
        declareScience.setDeclareId(declareId);

        DeclareScience declareScienceOld = declareScienceMapper.getByDeclareId(declareId);
        if (!Objects.isNull(declareScienceOld)) {
            declareScience.setId(declareScienceOld.getId());
            declareScienceMapper.updateByPrimaryKeySelective(declareScience);
        } else {
            declareScienceMapper.insertSelective(declareScience);
        }

    }

    @Override
    public void saveDeclareClassicCase(Integer declareId, DeclareClassicCaseReq classicCaseReq) {
        if (Objects.isNull(classicCaseReq)) {
            return;
        }
        DeclareClassicCase classicCase = new DeclareClassicCase();
        BeanUtils.copyProperties(classicCaseReq, classicCase);
        //典型案例 - 案例图片
        classicCase.setCaseImages(attachmentService.uploadAttachment(declareId, classicCaseReq.getCaseImages()));
        classicCase.setDeclareId(declareId);

        DeclareClassicCase classicCaseOld = classicCaseMapper.getByDeclareId(declareId);
        if (!Objects.isNull(classicCaseOld)) {
            classicCase.setId(classicCaseOld.getId());
            classicCaseMapper.updateByPrimaryKeySelective(classicCase);
        } else {
            classicCaseMapper.insertSelective(classicCase);
        }

    }

    @Override
    public void saveDeclareWeatherBureau(Integer declareId, DeclareWeatherBureauReq weatherBureauReq) {
        if (Objects.isNull(weatherBureauReq)) {
            return;
        }
        DeclareWeatherBureau weatherBureau = new DeclareWeatherBureau();
        BeanUtils.copyProperties(weatherBureauReq, weatherBureau);
        weatherBureau.setPrepareFiles(attachmentService.uploadAttachment(declareId, weatherBureauReq.getPrepareFiles()));
        weatherBureau.setDeclareId(declareId);

        DeclareWeatherBureau weatherBureauOld = weatherBureauMapper.getByDeclareId(declareId);
        if (!Objects.isNull(weatherBureauOld)) {
            weatherBureau.setId(weatherBureauOld.getId());
            weatherBureauMapper.updateByPrimaryKeySelective(weatherBureau);
        } else {
            weatherBureauMapper.insertSelective(weatherBureau);
        }
    }

    @Override
    public void saveDeclareUpgrade(Integer declareId, DeclareUpgradeReq upgradeReq) {
        if (Objects.isNull(upgradeReq)) {
            return;
        }
        DeclareUpgrade upgrade = new DeclareUpgrade();
        BeanUtils.copyProperties(upgradeReq, upgrade);
        upgrade.setDeclareId(declareId);
        //乡镇预警图片
        upgrade.setCountryWarningImages(attachmentService.uploadAttachment(declareId, upgradeReq.getCountryWarningImages()));
        //分乡镇-服务机制-文件
        upgrade.setCountryServiceFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getCountryServiceFiles()));
        //落实到位证明材料
        upgrade.setCountryProveFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getCountryProveFiles()));
        //落实到位证明图片
        upgrade.setCountryProveImages(attachmentService.uploadAttachment(declareId,upgradeReq.getCountryProveImages()));
        //网格-直达推送图片
        upgrade.setGridPushImages(attachmentService.uploadAttachment(declareId, upgradeReq.getGridPushImages()));

        //工作职责
        upgrade.setGridWorkDuty(attachmentService.uploadAttachment(declareId, upgradeReq.getGridWorkDuty()));

        //网格群众证明材料
        upgrade.setGridMassesFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getGridMassesFiles()));
        //网格群众证明图片
        upgrade.setGridMassesImages(attachmentService.uploadAttachment(declareId, upgradeReq.getGridMassesImages()));
        //排查图片
        upgrade.setWorryCheckImages(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryCheckImages()));
        //排查文件
        upgrade.setWorryCheckFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryCheckFiles()));
        //应急处理图片
        upgrade.setWorryHandleImages(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryHandleImages()));
        //应急处理文件
        upgrade.setWorryHandleFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryHandleFiles()));
        //信息反馈照片
        upgrade.setWorryBackImages(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryBackImages()));
        //信息反馈-文件
        upgrade.setWorryBackFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getWorryBackFiles()));
        //复核文件
        upgrade.setReviewFiles(attachmentService.uploadAttachment(declareId,upgradeReq.getReviewFiles()));
        //定期检查文件
        upgrade.setReviewCheckFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getReviewCheckFiles()));
        //定期检查照片
        upgrade.setReviewImages(attachmentService.uploadAttachment(declareId, upgradeReq.getReviewImages()));
        //培训照片
        upgrade.setGuideImages(attachmentService.uploadAttachment(declareId, upgradeReq.getGuideImages()));
        //培训文件
        upgrade.setGuideFiles(attachmentService.uploadAttachment(declareId, upgradeReq.getGuideFiles()));

        //科普图片
        upgrade.setGuideThemeImages(attachmentService.uploadAttachment(declareId, upgradeReq.getGuideThemeImages()));


        DeclareUpgrade upgradeOld = upgradeMapper.getByDeclareId(declareId);
        if (!Objects.isNull(upgradeOld)) {
            upgrade.setId(upgradeOld.getId());
            upgradeMapper.updateByPrimaryKeySelective(upgrade);
        } else {
            upgradeMapper.insertSelective(upgrade);
        }
    }

    @Transactional
    @Override
    public Declare update(Integer userId, DeclareReq declareReq) {
        if (declareReq.getId() == null || declareReq.getId() < 0) {
            throw new BizException(-1, "申报id参数缺失!");
        }

        Declare declare = declareMapper.selectByPrimaryKey(declareReq.getId());
        if (Objects.isNull(declare)) {
            throw new BizException(-1, "申报记录不存在或已删除!");
        }
        //主表

        //保存基础信息
        saveDeclareBasic(declare.getId(), declareReq.getBasicReq());
        //如果是正常申报
        if (declareReq.getDeclareType().equals(DeclareTypeEnum.NORMAL.getKey())) {
            //制度机制
            saveDeclareInstitution(declare.getId(), declareReq.getInstitutionReq());
            //防灾准备
            saveDeclareDisasterPlan(declare.getId(), declareReq.getDisasterPlanReq());
            //防灾设施
            saveDeclareDisasterFacilities(declare.getId(), declareReq.getFacilitiesReq());
            //科普培训
            saveDeclareScience(declare.getId(), declareReq.getScienceReq());
            //典型案例
            saveDeclareClassicCase(declare.getId(), declareReq.getCaseReq());
            //区县气象局
            saveDeclareWeatherBureau(declare.getId(), declareReq.getWeatherBureauReq());
            //提标升级
            saveDeclareUpgrade(declare.getId(), declareReq.getUpgradeReq());
        } else {
            //提标升级
            saveDeclareUpgrade(declare.getId(), declareReq.getUpgradeReq());
        }
        //修改日志
        saveLog(declare, DeclareLogTypeEnum.TYPE_11);
        return declare;
    }

    @Transactional
    @Override
    public boolean delete(Integer declareId) {
        Declare declare = declareMapper.selectByPrimaryKey(declareId);
        if (Objects.isNull(declare)) {
            throw new BizException(-1, "申报记录不存在或已删除!");
        }
        //主表
        declareMapper.deleteByPrimaryKey(declareId);
        //基础表
        declareBasicMapper.deleteByDeclareId(declareId);
        institutionMapper.deleteByDeclareId(declareId);
        disasterPlanMapper.deleteByDeclareId(declareId);
        disasterFacilitiesMapper.deleteByDeclareId(declareId);
        declareScienceMapper.deleteByDeclareId(declareId);
        classicCaseMapper.deleteByDeclareId(declareId);
        weatherBureauMapper.deleteByDeclareId(declareId);
        upgradeMapper.deleteByDeclareId(declareId);
        //附件表
        attachmentService.deleteByDeclareId(declare.getId());
        //日志表
        declareLogService.deleteByDeclareId(declare.getId());
        return true;
    }

    @Transactional
    @Override
    public Boolean submitArea(Integer id) {
        Declare declare = declareMapper.selectByPrimaryKey(id);
        if (Objects.isNull(declare)) {
            throw new BizException(-1, "申报记录不存在或已删除!");
        }
        if (declare.getScoreStatus().equals(DeclareScoreStatusEnum.AREA_WAIT.getKey())) {
            throw new BizException(-1, "已提交上级,勿重复操作!");
        }
        AdminDO adminDO = adminMapper.selectByPrimaryKey(ShiroUtils.getUserId());

        Declare declareUpdate = new Declare();
        declareUpdate.setId(declare.getId());
        declareUpdate.setScoreStatus(DeclareScoreStatusEnum.AREA_WAIT.getKey());
        //提交区域
        declareUpdate.setIsSubmitArea(1);
        declareMapper.updateByPrimaryKeySelective(declareUpdate);
        //记录日志
        //上级
        Region region = regionMapper.selectByPrimaryKey(declare.getAreaId());
        DeclareLog declareLog = new DeclareLog();
        declareLog.setDeclareId(declare.getId());
        declareLog.setUserLevel(adminDO.getMemberLevel());
        declareLog.setUserLevelName(adminDO.getVillageName());
        declareLog.setContent("提交申报至【"+region.getRegionName()+"】");
        declareLog.setOperatorType(DeclareLogTypeEnum.TYPE_12.getKey());
        logService.insertLog(declareLog);
        return true;
    }


    /**
     * 详情  -  如果退回  有退回原因
     * @param id
     * @param source 来源
     * @return
     */
    @Override
    public DeclareDetailVO detail(Integer id, String source) {
        Declare declare = declareMapper.selectByPrimaryKey(id);
        if (Objects.isNull(declare)) {
            throw new BizException(-1, "申报记录不存在或已删除!");
        }

        //主-申报表
        DeclareDetailVO declareDetailVO = new DeclareDetailVO();
        BeanUtils.copyProperties(declare, declareDetailVO);
        declareDetailVO.setCreateTimeStr(DateUtils.formatDate(declare.getCreateTime()));
        declareDetailVO.setRegionName(regionsService.getDeclareRegionName(declare, source));
        //申报材料动态信息
        declareDetailVO.setLogList(declareLogService.findByDeclareId(id));
        if (!source.equals(MemberLevelEnum.USER.getKey()) ) {
            //查询评分信息
            declareDetailVO.setScoreList(declareScoreService.findByDeclareId(id));
        }

        //主模块-打分信息
        List<ScoreListVO> scoreListVOList = declareScoreService.findByDeclareId(id);
        //模块评分配置
        List<ScoreParam> scoreParamList = scoreParamService.selectAll();

        //基础信息
        DeclareBasic declareBasic = declareBasicMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(declareBasic)) {
            DeclareBasicVO declareBasicVO = new DeclareBasicVO();
            BeanUtils.copyProperties(declareBasic, declareBasicVO);

            //回退信息
            declareBasicVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M00000.getName(),null));
            declareDetailVO.setBasicVO(declareBasicVO);
        }

        //如果是正常申报
        //制度机制
        DeclareInstitution declareInstitution = institutionMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(declareInstitution)) {
            DeclareInstitutionVO declareInstitutionVO = new DeclareInstitutionVO();
            BeanUtils.copyProperties(declareInstitution, declareInstitutionVO);
            //工作机制文件
            declareInstitutionVO.setOrgWorkFiles(attachmentService.getAttachments(declareInstitution.getOrgWorkFiles()));
            //重点单位
            if (!StringUtils.isEmpty(declareInstitution.getHotCompanys())) {
                List<DeclareInstitutionHotCompanyVO> hotCompanyVO = JSONObject.parseArray(declareInstitution.getHotCompanys(), DeclareInstitutionHotCompanyVO.class);
                declareInstitutionVO.setHotCompany(hotCompanyVO);
            }
            //服务站图片
            declareInstitutionVO.setStationImages(attachmentService.getAttachments(declareInstitution.getStationImages()));
            //投资证明文件
            declareInstitutionVO.setEnsureFiles(attachmentService.getAttachments(declareInstitution.getEnsureFiles()));
            //投资证明图片
            declareInstitutionVO.setEnsureImages(attachmentService.getAttachments(declareInstitution.getEnsureImages()));

            //回退信息
            declareInstitutionVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M10000.getName(), null));
            //用户申报 不用查询
            if (!source.equals(MemberLevelEnum.USER.getKey()) ) {
                //评分信息
                declareInstitutionVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M10000.getName(), scoreListVOList));
                //子模块 组织建设评分 - 打分信息
                declareInstitutionVO.setOrgScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10001.getName(), scoreParamList));
                //子模块 气象员信息 - 打分信息
                declareInstitutionVO.setWeatherPersonScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10002.getName(), scoreParamList));
                //子模块 重点单位 - 打分信息
                declareInstitutionVO.setHotCompanyScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10003.getName(), scoreParamList));
                //子模块 气象服务站 - 打分信息
                declareInstitutionVO.setStationScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10004.getName(), scoreParamList));
                //子模块 传播网络 - 打分信息
                declareInstitutionVO.setSpreadScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10005.getName(), scoreParamList));
                //子模块 组织保障 - 打分信息
                declareInstitutionVO.setEnsureScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M10006.getName(), scoreParamList));
            }

            declareDetailVO.setInstitutionVO(declareInstitutionVO);
        }

        //防灾准备
        DeclareDisasterPlan disasterPlan = disasterPlanMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(disasterPlan)) {
            DeclareDisasterPlanVO disasterPlanVO = new DeclareDisasterPlanVO();
            BeanUtils.copyProperties(disasterPlan, disasterPlanVO);
            //风险地图
            disasterPlanVO.setMapImages(attachmentService.getAttachments(disasterPlan.getMapImages()));
            //应急预案或计划
            disasterPlanVO.setPlanFiles(attachmentService.getAttachments(disasterPlan.getPlanFiles()));
            //现场照片
            disasterPlanVO.setTrainImages(attachmentService.getAttachments(disasterPlan.getTrainImages()));
            //回退信息
            disasterPlanVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M20000.getName(), null));

            //用户申报 不用查询
            if (!source.equals(MemberLevelEnum.USER.getKey()) ) {
                //评分信息
                disasterPlanVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M20000.getName(), scoreListVOList));
                //子模块 风险地图 - 打分信息
                disasterPlanVO.setMapScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M20001.getName(), scoreParamList));
                //子模块 应急预案 - 打分信息
                disasterPlanVO.setPlanScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M20002.getName(), scoreParamList));
                //子模块 应急演练 - 打分信息
                disasterPlanVO.setTrainScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M20003.getName(), scoreParamList));
            }

            declareDetailVO.setDisasterPlanVO(disasterPlanVO);
        }

        //防灾设施
        DeclareDisasterFacilities facilities = disasterFacilitiesMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(facilities)) {
            DeclareDisasterFacilitiesVO facilitiesVO = new DeclareDisasterFacilitiesVO();
            BeanUtils.copyProperties(facilities, facilitiesVO);
            //现场照片
            facilitiesVO.setInfoImages(attachmentService.getAttachments(facilities.getInfoImages()));
            //避灾-现场照片
            facilitiesVO.setPlanImages(attachmentService.getAttachments(facilities.getPlanImages()));
            //警示-照片
            facilitiesVO.setRemindImages(attachmentService.getAttachments(facilities.getRemindImages()));

            //回退信息
            facilitiesVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M30000.getName(), null));

            //用户申报 不用查询
            if (!source.equals(MemberLevelEnum.USER.getKey()) ) {
                //评分信息
                facilitiesVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M30000.getName(), scoreListVOList));
                //子模块 信息收发 - 打分信息
                facilitiesVO.setInfoScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M30001.getName(), scoreParamList));
                //子模块 避灾设施 - 打分信息
                facilitiesVO.setPlanScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M30002.getName(), scoreParamList));
                //子模块 防雷警示 - 打分信息
                facilitiesVO.setRemindScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M30003.getName(), scoreParamList));
            }

            declareDetailVO.setFacilitiesVO(facilitiesVO);
        }

        //科普培训
        DeclareScience science = declareScienceMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(science)) {
            DeclareScienceVO scienceVO = new DeclareScienceVO();
            BeanUtils.copyProperties(science, scienceVO);
            //培训照片
            scienceVO.setTrainImages(attachmentService.getAttachments(science.getTrainImages()));
            //培训证明文件
            scienceVO.setTrainFiles(attachmentService.getAttachments(science.getTrainFiles()));
            //科普图片
            scienceVO.setScienceImages(attachmentService.getAttachments(science.getScienceImages()));

            //回退信息
            scienceVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M40000.getName(), null));

            //用户申报 不用查询
            if (!source.equals(MemberLevelEnum.USER.getKey()) ) {
                //评分信息
                scienceVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M40000.getName(), scoreListVOList));
                //子模块 培训 - 打分信息
                scienceVO.setTrainScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M40001.getName(), scoreParamList));
                //子模块 科普 - 打分信息
                scienceVO.setScienceScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M40002.getName(), scoreParamList));
            }

            declareDetailVO.setScienceVO(scienceVO);
        }

        //典型案例
        DeclareClassicCase classicCase = classicCaseMapper.getByDeclareId(declare.getId());
        if (!Objects.isNull(classicCase)) {
            DeclareClassicCaseVO classicCaseVO = new DeclareClassicCaseVO();
            BeanUtils.copyProperties(classicCase, classicCaseVO);
            //案例图片
            classicCaseVO.setCaseImages(attachmentService.getAttachments(classicCase.getCaseImages()));

            //回退信息
            classicCaseVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M50000.getName(), null));
            //用户申报 不用查询
            if (!source.equals(MemberLevelEnum.USER.getKey())) {
                //评分信息
                classicCaseVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M50000.getName(), scoreListVOList));

                //子模块 典型案例 - 打分信息
                classicCaseVO.setCaseScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M50000.getName(), scoreParamList));
            }

            declareDetailVO.setCaseVO(classicCaseVO);
        }

        // 区县 气象局评分
        DeclareWeatherBureau weatherBureau = weatherBureauMapper.getByDeclareId(declare.getId());
        DeclareWeatherBureauVO bureauVO = new DeclareWeatherBureauVO();
        if (Objects.nonNull(weatherBureau)) {
            BeanUtils.copyProperties(weatherBureau, bureauVO);
            //应急准备认证文件
            bureauVO.setPrepareFiles(attachmentService.getAttachments(weatherBureau.getPrepareFiles()));
            //回退信息
            bureauVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M60000.getName(), null));
        }
        if (!source.equals(MemberLevelEnum.USER.getKey())) {
            //评分信息
            bureauVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M60000.getName(), scoreListVOList));
        }
        //子模块 气象信息上报统计 - 打分信息
        bureauVO.setReportScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60001.getName(), scoreParamList));
        //子模块 气象检测设施建设 - 打分信息
        bureauVO.setTestScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60002.getName(), scoreParamList));
        //子模块 气象灾害应急准备认证 - 打分信息
        bureauVO.setPrepareScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60003.getName(), scoreParamList));
        //子模块 居民住宅防雷装置安装 - 打分信息
        bureauVO.setThunderScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60004.getName(), scoreParamList));
        //子模块 公共场所防雷装置安装 - 打分信息
        bureauVO.setPublicThunderScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60005.getName(), scoreParamList));
        //子模块 气象信息上报统计 - 打分信息
        bureauVO.setSpreadRateScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M60006.getName(), scoreParamList));
        declareDetailVO.setWeatherBureauVO(bureauVO);

        //提标升级
        DeclareUpgrade upgrade = upgradeMapper.getByDeclareId(declare.getId());
        DeclareUpgradeVO upgradeVO = new DeclareUpgradeVO();
        if (Objects.nonNull(upgrade)) {
            BeanUtils.copyProperties(upgrade, upgradeVO);
            //乡镇预警图片
            upgradeVO.setCountryWarningImages(attachmentService.getAttachments(upgrade.getCountryWarningImages()));
            //分乡镇-服务机制-文件
            upgradeVO.setCountryServiceFiles(attachmentService.getAttachments(upgrade.getCountryServiceFiles()));
            //落实到位证明材料
            upgradeVO.setCountryProveFiles(attachmentService.getAttachments(upgrade.getCountryProveFiles()));
            //落实到位证明图片
            upgradeVO.setCountryProveImages(attachmentService.getAttachments(upgrade.getCountryProveImages()));
            //网格-直达推送图片
            upgradeVO.setGridPushImages(attachmentService.getAttachments(upgrade.getGridPushImages()));
            //工作职责
            upgradeVO.setGridWorkDuty(attachmentService.getAttachments(upgrade.getGridWorkDuty()));
            //网格群众证明材料
            upgradeVO.setGridMassesFiles(attachmentService.getAttachments(upgrade.getGridMassesFiles()));
            //网格群众证明图片
            upgradeVO.setGridMassesImages(attachmentService.getAttachments(upgrade.getGridMassesImages()));
            //排查图片
            upgradeVO.setWorryCheckImages(attachmentService.getAttachments(upgrade.getWorryCheckImages()));
            //排查文件
            upgradeVO.setWorryCheckFiles(attachmentService.getAttachments(upgrade.getWorryCheckFiles()));
            //应急处理图片
            upgradeVO.setWorryHandleImages(attachmentService.getAttachments(upgrade.getWorryHandleImages()));
            //应急处理文件
            upgradeVO.setWorryHandleFiles(attachmentService.getAttachments(upgrade.getWorryHandleFiles()));
            //信息反馈照片
            upgradeVO.setWorryBackImages(attachmentService.getAttachments(upgrade.getWorryBackImages()));
            //信息反馈-文件
            upgradeVO.setWorryBackFiles(attachmentService.getAttachments(upgrade.getWorryBackFiles()));
            //复核文件
            upgradeVO.setReviewFiles(attachmentService.getAttachments(upgrade.getReviewFiles()));
            //定期检查文件
            upgradeVO.setReviewCheckFiles(attachmentService.getAttachments(upgrade.getReviewCheckFiles()));
            //定期检查照片
            upgradeVO.setReviewImages(attachmentService.getAttachments(upgrade.getReviewImages()));
            //培训照片
            upgradeVO.setGuideImages(attachmentService.getAttachments(upgrade.getGuideImages()));
            //培训文件
            upgradeVO.setGuideFiles(attachmentService.getAttachments(upgrade.getGuideFiles()));
            //常态化图片
            upgradeVO.setGuideThemeImages(attachmentService.getAttachments(upgrade.getGuideThemeImages()));
            //回退信息
            upgradeVO.setReturnInfos(declareReturnService.findModuleByDeclareId(declare.getId(), DeclareModuleEnum.M70000.getName(), null));
        }
        if (!source.equals(MemberLevelEnum.USER.getKey())) {
            //评分信息
            upgradeVO.setScoreInfos(declareScoreService.scoreModule(DeclareModuleEnum.M70000.getName(), scoreListVOList));
        }
        //子模块 预警分乡镇 - 打分信息
        upgradeVO.setCountryWarningScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M70001.getName(), scoreParamList));
        //子模块 网格+气象 - 打分信息
        upgradeVO.setGridScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M70002.getName(), scoreParamList));
        //子模块 应急联动反馈 - 打分信息
        upgradeVO.setWorryCheckScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M70003.getName(), scoreParamList));
        //子模块 复核检查 - 打分信息
        upgradeVO.setReviewScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M70004.getName(), scoreParamList));
        //子模块 宣传指导 - 打分信息
        upgradeVO.setGuideScoreInfo(declareScoreService.subScoreModule(declare.getId(), DeclareModuleEnum.M70005.getName(), scoreParamList));
        declareDetailVO.setUpgradeVO(upgradeVO);
        return declareDetailVO;
    }

    @Override
    public boolean isSubmitDeclare(Integer userId) {
        //是否开启
        SysParam sysParam = sysParamService.declareSwitch();
        if (Objects.isNull(sysParam) || sysParam.getValue().equals("false")) {
            throw new BizException(-1, "暂未开启申报,请稍等!");
        }

        Integer startTime = sysParamService.getCurrentDeclareStartTime();
        Map<String,Object> params = new HashMap<>();
        params.put("createId", userId);
        params.put("startTime", DateUtils.dateFormatStr(startTime));
        Integer i = declareMapper.countByMap(params);
        if (i > 0) {
            throw new BizException(-1, "你已经申报过了,请勿重复申报!");
        }
        return true;
    }

    @Override
    public Declare getCurrentDeclare(Integer userId, Integer startTime) {
        Map<String,Object> params = new HashMap<>();
        params.put("createId", userId);
        params.put("isSubmitArea", 1);
        params.put("startTime", DateUtils.dateFormatStr(startTime));
        List<Declare> declares = declareMapper.selectByMap(params);
        if (CollectionUtils.isEmpty(declares)) {
            return null;
        }
        return declares.get(0);
    }

    /**
     * 新增修改时 评分规则 -查看调用
     * @param moduleName
     * @return
     */
    @Override
    public String getScoreRule(String moduleName) {
        ScoreParam scoreParam = scoreParamService.getByModuleName(moduleName);
        if (Objects.isNull(scoreParam)) {
            return "";
        }
        return scoreParam.getScoreRule();
    }
}
